import { Body, Controller, Ip, Post, Req } from '@nestjs/common';
import { LoginService } from './login.service';
//import { CachingService } from '../caching/caching.service';
import { UtilsService } from '@app/utils';
import { User } from '@app/db/entities/User';
import { DbService } from '../db/db.service';
import { WechatService } from '../wechat/wechat.service';
import { AlipayService } from '../alipay/alipay.service';
import { UserService } from '../user/user.service';

@Controller('login')
export class LoginController {
    constructor(
        private userService:UserService,
        private readonly db:DbService,
        private service:LoginService,
        //private cache:CachingService,
        private utils:UtilsService,
        private wechat:WechatService,
        private alipay:AlipayService
    ){
        
    }

    
    @Post()
    async login(@Body('code') code:string, @Req() { isWx }, @Ip() ip:string){
        // const lockKey = 'l:' + ip
        // const lock = await this.cache.set(lockKey, '1', 10, 'NX')
        // if(!lock) return
        //console.log('---------')
        const data = isWx ? (await this.wechat.login(code)) : (await this.alipay.login(code))
        if(!data) return this.utils.failRes()

        //console.log(data)

        let openid = isWx ? data.openid : data.userId

        let time = this.utils.time()

        let user:KeyToValueType<User> = await this.db.user.findOne({openid : openid}, ['id', 'source', 'nickname', 'avatar', 'phone'])

        if(!user) { //还没有的
            user = {
                openid,
                source : isWx ? 1 : 2,
                registerTime : time,
                nickname : '',
                avatar : '',
                phone : null
                //lastIp : ip
            }
            const res = await this.db.user.insert(user)

            if(!res) {
                return this.utils.failRes()
            }

            user.id = res.rows[0].id
        }else {
            this.db.user.update({id : user.id}, {
                lastLoginTime : time,
                //lastIp : ip
            })
        }

        let cacheData:any = {
            source : user.source,
            openid : openid
        }

        if(isWx) {
            cacheData.session_key = data.session_key
            
            if(data.unionid) {
                cacheData.unionid = data.unionid
            }
        }else {

        }

        this.userService.setCache(user.id, cacheData)

        const {accessToken, refreshToken, expire} = this.service.makeToken(user.id, time)

        return this.utils.successRes({
            accessToken,
            refreshToken,
            expire,
            user : {
                nickname : user.nickname,
                avatar : user.avatar,
                phoneAuth : user.phone != null
            }
        })
        

    }
}
